package no29;

import java.util.Arrays;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/4/25 15:46
 * 顺时针打印矩阵
 * https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/
 */
public class Solution {

    public static int[] spiralOrder(int[][] matrix) {
        // 边界处理
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[0];
        }
        // 定义左上角位置和右下角位置
        int x1 = 0;
        int y1 = 0;
        int x2 = matrix.length - 1;
        int y2 = matrix[0].length - 1;
        // 顺时针打印矩阵
        int[] ret = new int[matrix.length * matrix[0].length];
        int index = 0;
        while (index < ret.length) {
            // 上侧
            for (int i = y1; i <= y2; i++) {
                ret[index++] = matrix[x1][i];
            }
            // 右侧
            for (int i = x1 + 1; i <= x2; i++) {
                ret[index++] = matrix[i][y2];
            }
            // 至少还剩两行的时候, 存储下侧
            if (x2 > x1) {
                for (int i = y2 - 1; i >= y1; i--) {
                    ret[index++] = matrix[x2][i];
                }
            }
            // 至少还剩两列的时候, 存储左侧
            if (y2 > y1) {
                for (int i = x2 - 1; i >= x1 + 1; i--) {
                    ret[index++] = matrix[i][y1];
                }
            }
            // 更新边界
            x1++;
            y1++;
            x2--;
            y2--;
        }
        // 返回结果
        return ret;
    }

    public static void main(String[] args) {
        int[][] matrix = new int[][]{{1, 2 ,3, 4}, {5 ,6, 7, 8}, {9, 10, 11, 12}};
        int[] spiralOrder = spiralOrder(matrix);
        System.out.println(Arrays.toString(spiralOrder));
    }
}
